﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using Top.Api;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using System.Collections;
using DBControl;
using System.Data;

namespace KSGJ.AjaxCommand
{
    /// <summary>
    /// clearAlltag 的摘要说明
    /// </summary>
    public class clearAlltag : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        private static ITopClient client = new DefaultTopClient(WebConfigurationManager.AppSettings["AppUrl"].ToString(), WebConfigurationManager.AppSettings["AppKey"].ToString(), WebConfigurationManager.AppSettings["AppSecret"].ToString());
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string usersessionkey = "";
            if (context.Session["sessionKey"] != null)
            {
                usersessionkey = context.Session["sessionKey"].ToString();
            }
            else if (context.Session["ParentsessionKey"] != null)
            {
                usersessionkey = context.Session["ParentsessionKey"].ToString();
            }

            ItemsOnsaleGetRequest onsellreq = new ItemsOnsaleGetRequest();
            onsellreq.Fields = "num_iid";
            int deltagcount = 0;
            ItemsOnsaleGetResponse onSellRes = client.Execute(onsellreq, usersessionkey);
            List<long> activetagid = new List<long>();
            SqlDbHelper sdh = new SqlDbHelper();
            foreach (var item in onSellRes.Items)
            {
                //当前商品所有的优惠策略
                List<Promotion> currentlist = getTaobaoPromotion(item.NumIid.ToString(), usersessionkey);
                //当前商品过期的优惠策略
                List<Promotion> overpromotion = currentlist.FindAll(delegate(Promotion p) { return DateTime.Parse(p.EndDate) < DateTime.Now && p.Status == "ACTIVE"; });
                //当前商品未过期的优惠策略
                List<Promotion> activepromotion = currentlist.FindAll(delegate(Promotion p) { return DateTime.Parse(p.EndDate) >= DateTime.Now && p.Status == "ACTIVE"; });
                foreach (var dellist in overpromotion)
                {
                    bool isdel = delPromotion(dellist.PromotionId, usersessionkey);
                    if (isdel)
                    {
                        string delpro = "DELETE Promotion WHERE Pid = '" + dellist.PromotionId + "'";
                        sdh.ExecuteNonQuery(delpro);
                    }
                }
                foreach (var activelist in activepromotion)
                {
                    if (!activetagid.Contains(activelist.TagId))
                    {
                        activetagid.Add(activelist.TagId);
                    }
                }
            }

            List<UserTag> allTag = getTag(usersessionkey);
            foreach (var tagi in allTag)
            {
                if (!activetagid.Contains(tagi.TagId))
                {
                    bool delt = delTag(usersessionkey, tagi.TagId);
                    if (delt)
                    {
                        deltagcount = deltagcount + 1;
                    }
                }
            }

            context.Response.Write("您已删除" + deltagcount + "个过期人群");
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private List<Promotion> getTaobaoPromotion(string numid, string sessionkey)
        {
            MarketingPromotionsGetRequest req = new MarketingPromotionsGetRequest();
            req.Fields = "promotion_id, promotion_title, num_iid,end_date, tag_id, status";
            req.NumIid = numid;
            //req.Status = "ACTIVE";
            MarketingPromotionsGetResponse response = client.Execute(req, sessionkey);
            return response.Promotions;
            //return response.Promotions.FindAll(delegate(Promotion p) { return DateTime.Parse(p.EndDate) < DateTime.Now && p.Status == "ACTIVE"; });
        }

        private Boolean delPromotion(long pid, string sessionkey)
        {
            MarketingPromotionDeleteRequest req = new MarketingPromotionDeleteRequest();
            req.PromotionId = pid;
            MarketingPromotionDeleteResponse response = client.Execute(req, sessionkey);
            if (response.IsError) { return false; }
            return true;
        }

        protected List<UserTag> getTag(string sessionkey)
        {
            MarketingTagsGetRequest tagget = new MarketingTagsGetRequest();
            tagget.Fields = "tag_id,tag_name,create_date,description";
            MarketingTagsGetResponse tagresp = client.Execute(tagget, sessionkey);
            return tagresp.UserTags;
        }

        private bool delTag(string sessionkey, long tid)
        {
            MarketingTagDeleteRequest utd = new MarketingTagDeleteRequest();
            utd.TagId = tid;
            MarketingTagDeleteResponse utr = client.Execute(utd, sessionkey);
            if (utr.IsError)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}